const express = require('express');
const router = express.Router();
const db = require('../db/db');

router.get('/login', (req, res) => {
    res.render('login')
})

router.post('/api/login', async (req, res) => {
    let setRes = await db.User.Model.find({ account: req.body.account })
        .then(result => result)
        .catch(err => console.log('注册失败', err));
    if (setRes.length > 0) {
        res.send({ code: 5001, message: '账号已被注册，请更换一个！' })
        return;
    }
    let user = new db.User.Model({
        name: req.body.name,
        password: req.body.password,
        account: req.body.account,
        createTime: new Date().getTime(),
        _id: new db.Mongoose.Types.ObjectId()
    }).save()
        .then((result) => {
            console.log('注册账号成功', result)
            res.send({ code: 0, message: '创建成功，请登录' })
        })
        .catch(err => {
            console.log('注册账号失败', result)
        })

})

module.exports = router;
